<template>
    <Row :gutter="8">
        <Col span="16">
            <Card>
                <p slot="title">
                    <Icon type="ios-film-outline"></Icon>
                    网页资料
                </p>
                <br>
                <Row :gutter="8">
                    <Col span="8">&nbsp;</Col>
                    <Col span="8">
                        <Input v-model="keywords" @keyup.enter.native="handleSearch(1)" placeholder="请输入关键字">
                            <Icon type="ios-search-strong" slot="prepend" style="padding:0px 10px;"></Icon>
                        </Input>
                    </Col>
                    <Col span="8">&nbsp;</Col>
                </Row>
                <br>
                <br>
                <Row :gutter="8">
                    <Col span="24">
                        <Page @on-change="changePage" :current="page.current" :total="page.total" :page-size="page.pagesize" show-total show-elevator></Page>
                    </Col>
                </Row>
                <br>
                <Row :gutter="16">
                    <Col span="4" v-for="(item, index) in data" :key="index">
                        <Card style="width:100%;text-align:center;margin-bottom:15px;">
                            <div @click="handleFormdata (item.versionsid,item.version,item.remark)" style="cursor:pointer;">
                                <a>
                                    <h3>V {{item.version}}</h3>
                                </a>
                                <div style="color:gray;">{{item.createtime}}</div>
                            </div>
                        </Card>
                    </Col>
                </Row>
            </Card>
        </Col>

        <Col span="8">
            <Card>
                <p slot="title">
                    <Icon type="ios-film-outline"></Icon>
                    编辑
                </p>
                <br>
                <Row :gutter="8">
                    <Col span="24">
                        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                            <FormItem label="ID" prop="versionsid">
                                <Input v-model="formValidate.versionsid" placeholder="ID不可编辑" disabled></Input>
                            </FormItem>
                            <FormItem label="版本号" prop="version">
                                <Input v-model="formValidate.version" placeholder="请输入版本号"></Input>
                            </FormItem>
                            <FormItem label="更新内容" prop="remark">
                                <Input v-model="formValidate.remark" type="textarea" :autosize="{minRows: 12,maxRows: 25}" placeholder="请输入更新内容"></Input>
                            </FormItem>
                            <FormItem label="上传" prop="content">
                                <input id="content" @change="handleChangeContent" name="content" type="file"/>
                            </FormItem>
                            <FormItem>
                                <Button type="primary" @click="handleSubmit('formValidate')" :loading="save_loading">保存</Button>
                                <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                                <Button v-if="formValidate.version && formValidate.version>'1.0.4'" type="error" @click="handleUpdateto" style="margin-left: 8px">更新到此版本</Button>
                            </FormItem>
                        </Form>
                    </Col>
                </Row>
            </Card>
        </Col>
    </Row>
</template>

<script>
const {dialog} = require('electron').remote
const {ipcRenderer} = require('electron')
export default {
    name: 'version',
    data () {
        return {
            serverpath:'',
            key:'version',
            keywords:'',
            page: {
                total: 0,
                current: 1,
                pagesize: 8,
                //原代码为  key: 'username', 但不符合通用规则,修改成id为key,如有需要可以改正
                key: 'version',
                order: 'desc',
                pagesizeopts: [12, 24, 48, 96, 192, 384]
            },
            data: [],
            save_loading:false,
            formValidate: {
                versionsid:''
                ,version: ''
                ,remark: ''
                ,content: ''
                ,contentfile: null//文件对象
            },
            ruleValidate: {
                version: [
                    { required: true, message: '版本号不能为空', trigger: 'blur'  }
                ],
                remark: [
                    { required: true, message: '请输入更新内容', trigger: 'blur' },
                    { type: 'string', max: 500, message: '更新内容不能超过500个字', trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        handleSubmit (name) {
            this.save_loading = true;
            let self = this;
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let param = new FormData(); //创建form对象
                    param.append('versionsid',self.formValidate.versionsid);//ID
                    param.append('version',self.formValidate.version);//版本号
                    param.append('remark',self.formValidate.remark);//更新内容
                    param.append('file',self.formValidate.contentfile);//图片文件
                    self.$axios.post(self.$util.server+'versions/save',  param, {
                        headers: {
                            "authorization": localStorage.getItem("authorization"),
                            "Content-Type":"multipart/form-data"
                        }
                    }).then(function(response) {
                        self.save_loading = false;
                        if(response.data.ok){
                            self.$Message.success('保存成功!');
                            self.handleSearch(1);
                        }else{
                            self.$Message.error('保存失败，请检查输入内容!');
                        }
                    }).catch( function(response) {
                        self.$Message.error('保存失败，请检查输入内容!');
                        console.log(response)
                    });
                } else {
                    self.save_loading = false;
                    self.$Message.error('内容验证不通过，请检查输入内容!');
                }
            })
        },
        handleFormdata (versionsid,version,remark) {
            this.formValidate.versionsid = versionsid;//ID
            this.formValidate.version = version;//版本号
            this.formValidate.remark = remark;//描述
        },
        handleReset (name) {
            this.$refs[name].resetFields();
        },
        handleSearch (topage) {
            //初始化列表
            let self = this;
            let size = this.page.pagesize;
            if(topage) this.page.current = topage;
            let page = this.page.current-1;
            console.log(page)
            let sort = this.page.key + ',' + this.page.order;
            if(this.page.order=='normal'){ sort = 'version, desc';}
            let key = this.key;
            let keywords = this.keywords;

            this.$axios.get(self.$util.server+'versions/pagedata', {
                params:{
                    size: size,
                    page: page,
                    sort: sort,
                    key: key,
                    keywords: keywords
                },
                headers: {
                    "authorization": localStorage.getItem("authorization"),
                    "Content-Type":"application/json;charset=utf-8"
                }
            }).then(function(response) {
                if(response.data.total>0) {
                    self.page.total = response.data.total;
                    self.data = response.data.rows;
                    self.$Loading.finish();
                }else{
                    self.page.total = 0;
                    self.data = [];
                }
            }).catch( function(response) {
                console.log(response)
            });
        },
        handleChangeContent(e) {
            let file=e.target.files.item(0);
            this.formValidate.contentfile = file;
        },
        changePage(current){
            this.page.current = current;
            this.handleSearch();
        },
        handleUpdateto(){//软件更新
            let self = this;
            console.log('self.formValidate.version:'+self.formValidate.version);
            console.log('self.formValidate.content:'+self.formValidate.content);
            console.log('self.formValidate.remark:'+self.formValidate.remark);
            if(self.formValidate.version && self.formValidate.version>'1.0.2'){
                self.$Modal.confirm({
                    loading:true,
                    title:'软件恢复',
                    content:'确认恢复到当前版本吗？</br>版本记录：</br>'+self.formValidate.remark.replace(/\r\n/g,'</br>'),
                    onOk: function(){
                        let modal = this;
                        ipcRenderer.send('versioncontrol',self.formValidate.version+','+self.$util.server+self.formValidate.content);
                        modal.remove();
                    }
                });
            }else{
                this.$Message.warning({content: '只能恢复到具备自动更新功能的版本！', duration: 4})
            }
        },
        handleInit () {
            //初始化查询
            this.handleSearch()
        }
    },
    mounted () {
        //清除全部消息监听
        ipcRenderer.removeAllListeners('tips')

        let latestVersion = null;
        let currentVersion = localStorage.getItem('currentVersion');

        //软件更新
        let self = this;

        this.$axios.get(self.$util.server+'versions/latestversion', {
            params:{},
            headers: {
                "authorization": localStorage.getItem("authorization"),
                "Content-Type":"application/json;charset=utf-8"
            }
        }).then(function (response) {
            latestVersion = response.data.version;
            if(currentVersion<latestVersion){
                self.$Modal.confirm({
                    loading:true,
                    title:'软件更新',
                    content:'发现新版本：'+latestVersion+'，请尽早更新！</br>更新内容：</br>'+response.data.remark.replace(/\r\n/g,'</br>'),
                    onOk: function(){
                        let modal = this;
                        ipcRenderer.send('versioncontrol',response.data.version+','+self.$util.server+response.data.content)
                        modal.remove();
                    }
                });
            }
        }).catch(function (response) {
            console.log(response)
        })

        //接收消息
        ipcRenderer.on('tips', (event, content) => {
            if(("软件更新成功，更新内容重启软件后生效" == content || content.indexOf("当前版本与指定更新版本相同")!=-1)
                 && latestVersion){
                localStorage.setItem('currentVersion',latestVersion);
            }
            this.$Message.info({content: content, duration: 5})
        })

        this.handleInit();
    }

};
</script>
